import re

from fuzzywuzzy import process
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LAParams, LTTextBoxHorizontal
from pdfminer.pdfinterp import PDFResourceManager, PDFTextExtractionNotAllowed, PDFPageInterpreter
from pdfminer.pdfparser import PDFParser, PDFDocument
from fuzzywuzzy import fuzz

compareRatio = 40
eMailRatio = 50


# 解析单个文档
def parseDoc(doc):
    resultStr = []
    for p in doc.paragraphs:
        text = parseDocParagraph(p)
        if str.strip(text):
            info2 = re.sub(r'\s+', ' ', str.strip(text), 0)
            info3 = re.sub(r'[/=|/？|/。|/，|/；|/!|/~|/^|/*|/?|/#|/;|/&|/,/，/：/—/:]', '', info2, 0)
            resultStr.append(info3)
    for table in doc.tables:
        for row in table.rows:
            rowcontent = []
            for cell in row.cells:
                if str.strip(cell.text):
                    rowcontent.append(cell.text)
            resultStr.append(rowcontent)

    return resultStr


def parseInfo(info):
    row = []
    name_location = info.find('名')
    row.append(subInfo(info, name_location, 1))

    sex_location = info.find('性别')
    row.append(subInfo(info, sex_location, 2))

    phone_location = info.find('联系方式')
    sub_num = 4
    if phone_location == -1:
        phone_location = info.find('手机')
        sub_num = 2
    if phone_location == -1:
        phone_location = info.find('电话')
        sub_num = 2
    row.append(subInfo(info, phone_location, sub_num))

    work_content_location = info.find('求职意向')
    row.append(subInfo(info, work_content_location, 4))

    college_location = info.find('毕业院校')
    row.append(subInfo(info, college_location, 4))

    specialty_location = info.find('专业')
    row.append(subInfo(info, specialty_location, 2))

    leave_school_location = info.find('毕业时间')
    row.append(subInfo(info, leave_school_location, 4))

    birth_day_location = info.find('出生年月')
    if birth_day_location == -1:
        birth_day_location = info.find('出生日期')
    row.append(subInfo(info, birth_day_location, 4))

    education_location = info.find('学历')
    row.append(subInfo(info, education_location, 2))

    return row


def parseDocParagraph(p):
    text = ''
    t_para = u""
    xml_str = str(p.paragraph_format.element.xml)
    wt_list = re.findall('<w:t[\S\s]*?</w:t>', xml_str)
    for wt in wt_list:
        wt_content = re.sub('<[\S\s]*?>', u"", wt)
        t_para += wt_content
    if t_para:
        text = text + t_para + '  '
    return text


# 截取对应值
def subInfo(info, location, start):
    if location != -1:
        findNum = info.find(' ', location, location + 30)
        # 要截取地方开始位置是空格 则开始位置加1
        while location + start == findNum:
            location = location + 1
            findNum = info.find(' ', findNum + 1, location + 30)
        if findNum > -1:
            if findNum < location + start:
                findNum = location + start + start
            # 处理key前有空格情况
            if findNum > start:
                subInformation = info[location + start:findNum]
                return subInformation
            else:
                subInformation = info[location + start:findNum]
                return subInformation
        else:
            subInformation = info[location + start:]
            return subInformation
    return ''


# 解析数组
def parseArrayInfo(infoArr):
    row = []
    # 字段匹配
    nameMatch = process.extractOne('姓 名', infoArr)
    homeTownMatch = process.extractOne('籍 贯', infoArr)
    birthdayMatch = process.extractOne('出生年月', infoArr)
    schoolMatch = process.extractOne('毕业院校', infoArr)
    if schoolMatch[1] < compareRatio:
        schoolMatch = process.extractOne('毕业学校', infoArr)
    specialtyMatch = process.extractOne('专 业', infoArr)
    if specialtyMatch[0].find('专') == -1 or specialtyMatch[0].find('业') == -1:
        specialtyMatch = process.extractOne('专业', infoArr)
    educationMatch = process.extractOne('学 历', infoArr)
    phoneMatch = process.extractOne('联系方式', infoArr)
    if phoneMatch[1] < compareRatio:
        phoneMatch = process.extractOne('联系电话', infoArr)
    if phoneMatch[1] < compareRatio:
        phoneMatch = process.extractOne('电 话', infoArr)
    sexMatch = process.extractOne('性 别', infoArr)
    workContentMatch = process.extractOne('求职意向', infoArr)
    if workContentMatch[1] < compareRatio:
        workContentMatch = process.extractOne('应聘岗位', infoArr)
    leaveSchoolTimeMatch = process.extractOne('毕业时间', infoArr)
    eMailMatch = process.extractOne('邮 箱', infoArr)
    if eMailMatch[0].find('邮') == -1 or eMailMatch[0].find('箱') == -1:
        eMailMatch = process.extractOne('邮箱', infoArr)
    if eMailMatch[1] < eMailRatio:
        eMailMatch = process.extractOne('Email', infoArr)
    print(infoArr)
    print(nameMatch)
    print(homeTownMatch)
    print(birthdayMatch)
    print(schoolMatch)
    print(specialtyMatch)
    print(educationMatch)
    print(phoneMatch)
    print(sexMatch)
    print(workContentMatch)
    print(leaveSchoolTimeMatch)
    print(eMailMatch)

    if nameMatch[1] > compareRatio:
        name_location = nameMatch[0].find('名')
        row.append(subInfo(nameMatch[0], name_location, 1))
    else:
        row.append('')
    if sexMatch[1] > compareRatio:
        sex_location = sexMatch[0].find('别')
        row.append(subInfo(sexMatch[0], sex_location, 1))
    else:
        row.append('')
    if phoneMatch[1] > compareRatio:
        start = 4
        phone_location = phoneMatch[0].find('联系方式')
        if phone_location == -1:
            phone_location = phoneMatch[0].find('联系电话')
        if phone_location == -1:
            start = 2
            phone_location = phoneMatch[0].find('电话')
        if phone_location == -1:
            phone_location = phoneMatch[0].find('话')
            start = 1
        row.append(subInfo(phoneMatch[0], phone_location, start))
    else:
        row.append('')
    if workContentMatch[1] > compareRatio:
        work_content_location = workContentMatch[0].find('求职意向')
        if work_content_location == -1:
            work_content_location = workContentMatch[0].find('应聘岗位')
        row.append(subInfo(workContentMatch[0], work_content_location, 4))
    else:
        row.append('')
    if schoolMatch[1] > compareRatio:
        school_location = schoolMatch[0].find('毕业院校')
        if school_location == -1:
            school_location = schoolMatch[0].find('毕业学校')
        row.append(subInfo(schoolMatch[0], school_location, 4))
    else:
        row.append('')
    if specialtyMatch[1] > compareRatio:
        specialty_location = specialtyMatch[0].find('业')
        row.append(subInfo(specialtyMatch[0], specialty_location, 1))
    else:
        row.append('')
    if leaveSchoolTimeMatch[1] > compareRatio:
        leave_school_location = leaveSchoolTimeMatch[0].find('毕业时间')
        row.append(subInfo(leaveSchoolTimeMatch[0], leave_school_location, 4))
    else:
        row.append('')
    if birthdayMatch[1] > compareRatio:
        birthday_location = birthdayMatch[0].find('出生年月')
        row.append(subInfo(birthdayMatch[0], birthday_location, 4))
    else:
        birthdayMatch = process.extractOne('出生日期', infoArr)
        if birthdayMatch[1] > compareRatio:
            birthday_location = birthdayMatch[0].find('出生日期')
            row.append(subInfo(birthdayMatch[0], birthday_location, 4))

        else:
            row.append('')
    if educationMatch[1] > compareRatio:
        education_location = educationMatch[0].find('历')
        row.append(subInfo(educationMatch[0], education_location, 1))
    else:
        row.append('')
    if homeTownMatch[1] > compareRatio:
        home_town_location = homeTownMatch[0].find('贯')
        row.append(subInfo(homeTownMatch[0], home_town_location, 1))
    else:
        row.append('')
    if eMailMatch[1] > compareRatio:
        email_location = eMailMatch[0].find('mail')
        start = 4
        if email_location == -1:
            email_location = eMailMatch[0].find('箱')
            start = 1
        row.append(subInfo(eMailMatch[0], email_location, start))
    else:
        row.append('')
    return row


def parserPdf(pdf_file):
    parser = PDFParser(pdf_file.stream)
    doc = PDFDocument()
    # 连接分析器，与文档对象
    parser.set_document(doc)
    doc.set_parser(parser)

    # 提供初始化密码，如果没有密码，就创建一个空的字符串
    doc.initialize()

    # 检测文档是否提供txt转换，不提供就忽略
    if not doc.is_extractable:
        raise PDFTextExtractionNotAllowed
    else:
        # 创建PDF，资源管理器，来共享资源
        rsrcmgr = PDFResourceManager()
        # 创建一个PDF设备对象
        laparams = LAParams()
        device = PDFPageAggregator(rsrcmgr, laparams=laparams)
        # 创建一个PDF解释其对象
        interpreter = PDFPageInterpreter(rsrcmgr, device)

        # 循环遍历列表，每次处理一个page内容
        # doc.get_pages() 获取page列表
        resultStr = []
        for page in doc.get_pages():
            interpreter.process_page(page)
            # 接受该页面的LTPage对象
            layout = device.get_result()
            # 这里layout是一个LTPage对象 里面存放着 这个page解析出的各种对象
            # 一般包括LTTextBox, LTFigure, LTImage, LTTextBoxHorizontal 等等
            # 想要获取文本就获得对象的text属性，
            for x in layout:
                if isinstance(x, LTTextBoxHorizontal):
                    textstr = x.get_text()
                    if str.strip(textstr):
                        info2 = re.sub(r'\s+', ' ', str.strip(textstr), 0)
                        info3 = re.sub(r'[/=|/？|/。|/，|/；|/!|/~|/^|/*|/?|/#|/;|/&|/,|/-/，/：/—/:|/\uf0d8]', '', info2, 0)
                    resultStr.append(info3)

    return resultStr


def parseException(excep, standard):
    # 使用排序 并模糊匹配
    degree = fuzz.partial_token_sort_ratio(standard, excep)
    return degree
